
var express = require('express');
var multer = require('multer');
var path = require('path');
var mkdirp = require('mkdirp');
var sd = require("silly-datetime")
var storage = multer.diskStorage({
    destination: async function (req, file, cb) {
        // 1. 获取当前日期
        let day = sd.format(new Date(), "YYYYMMDD"); 
        let dir = path.join("./public/uploads", day);

        //按照日期生成图片存储目录 mkdirp是异步方法   
        await mkdirp(dir);
        cb(null, dir)
    },
    filename: function (req, file, cb) {
        // 1. 获取文件后缀名
        let extName = path.extname(file.originalname)
        // 2. 根据时间戳生成文件名
        const uniqueSuffix = Date.now();
        cb(null, file.originalname.split('.',1) + '-' + uniqueSuffix + extName)
    }
})
var upload = multer({ storage: storage })
var router = express.Router();


router.post('/',upload.single('document'),(req,res,next)=>{
    res.send({data:req.file,message:'上传成功',command:'back to page'});
});
router.post('/multi',upload.array('document',10),(req,res,next)=>{
    res.send({data:req.file,message:'上传成功',command:'back to page'});
});


module.exports = router;
